package com.cz.fra.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cz.fra.entity.User;
import com.cz.fra.service.AccountService;
import com.cz.fra.service.ServiceException;
import com.cz.fra.service.impl.AccountServiceImpl;

public class RegisterServlet extends HttpServlet{

	 /**
	 *  
	 */
	private static final long serialVersionUID = 9162383129363421474L;
	
	AccountService accountService = new AccountServiceImpl();
	
	public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException{
	     String name = request.getParameter("username").trim();
	     String pwd =  request.getParameter("password").trim();
	     String email = request.getParameter("email").trim();
	     //String address = request.getParameter("address").trim();
	     
	     User user = new User();
	     user.setUsername(name);
	     user.setPassword(pwd);
	     user.setEmail(email);
	     //user.setAddress(address);
	     
	     PrintWriter out = response.getWriter();
	     
	     try {
			if(accountService.addAccountValidation(user)){
				if(accountService.addAccount(user).equals("success")){
					out.write("Success");
				}else{
					out.write("Failed");
				}
			}
			else{
				out.write("Failed/n");
				//Once found that username is already used, return all the registered username list to client
				// to make sure another server side check is unnecessary.
				for(String str:accountService.getUsernameList()){
					out.write(str+"/n");
				}
			}
		} catch (ServiceException e) {
			out.write("Failed");
			e.printStackTrace();
		}
	     
	}
	
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException{
		doGet(request,response);
	}
	
}
